<template>
  <div id="userLayout" :class="['user-layout-wrapper']">
    <div class="container">
      <div class="top">
        <div class="header">
          <a href="/">
            <img src="../../../static/images/login_icon.png" class="logo" alt="logo" />
            <span class="title">佳华物流集团 ERP</span>
            <img src="../../../static/images/login_plus.png" class="icon" alt />
          </a>
        </div>
        <div class="desc">
          <img src="../../../static/images/login_txt.png" class="special_img" alt />
        </div>
      </div>
      <div class="main">
        <a-form-model ref="loginForm" :model="form" :rules="rules">
          <a-form-model-item ref="name" prop="name">
            <a-input
              :max-length="11"
              class="login-input"
              v-model="form.name"
              placeholder="账户"
              @blur=" () => { $refs.name.onFieldBlur() }"
            >
              <a-icon slot="prefix" type="user" style="color:rgba(0,0,0,.25)" />
            </a-input>
          </a-form-model-item>
          <a-form-model-item ref="password" prop="password">
            <a-input
              class="login-input"
              v-model="form.password"
              type="password"
              placeholder="密码"
              @blur=" () => { $refs.password.onFieldBlur() }"
            >
              <a-icon slot="prefix" type="lock" style="color:rgba(0,0,0,.25)" />
            </a-input>
          </a-form-model-item>
          <a-form-model-item style="margin-bottom: 12px;">
            <a-button type="primary" block @click="onSubmit()">登录</a-button>
          </a-form-model-item>
        </a-form-model>
        <a @click="forgetPassword" class="forget-password">忘记密码</a>
      </div>
      <div class="footer">
        <div class="copyright">
          CopyRight &copy; 2020 江苏佳华物流发展有限公司
          <br />江苏易船货科技有限公司 技术支持
        </div>
      </div>
    </div>
    <a-modal
      title="找回密码"
      :visible="visible"
      :confirm-loading="confirmLoading"
      width="600px"
      :bodyStyle="bodyStyle"
      centered
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form-model ref="ruleForm" :model="ruleForm" :rules="forgetRules">
        <a-form-model-item prop="phone">
          <a-input
            style="height: 40px;"
            v-model="ruleForm.phone"
            type="phone"
            placeholder="手机号"
            :max-length="11"
          >
            <a-icon slot="prefix" type="mobile" style="color:rgba(0,0,0,.25)" />
          </a-input>
        </a-form-model-item>
        <a-form-model-item prop="code">
          <a-input
            style="height: 40px;width: 240px;"
            v-model="ruleForm.code"
            type="code"
            placeholder="验证码"
          >
            <a-icon slot="prefix" type="mail" style="color:rgba(0,0,0,.25)" />
          </a-input>
          <a-button
            type="primary"
            @click="getCode()"
            :disabled="codeStatus"
            style="float: right;height: 40px;width: 102px"
          >{{ count ? `${count}s` : '获取验证码'}}</a-button>
        </a-form-model-item>
        <a-form-model-item has-feedback prop="pass">
          <a-input style="height: 40px;" v-model="ruleForm.pass" type="password" placeholder="新密码">
            <a-icon slot="prefix" type="lock" style="color:rgba(0,0,0,.25)" />
          </a-input>
        </a-form-model-item>
        <a-form-model-item has-feedback prop="checkPass" style="margin:0;">
          <a-input
            style="height: 40px;"
            v-model="ruleForm.checkPass"
            type="password"
            placeholder="确认新密码"
          >
            <a-icon slot="prefix" type="lock" style="color:rgba(0,0,0,.25)" />
          </a-input>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!-- 修改密码 -->
    <a-modal
      title="修改密码"
      :visible="changePassword"
      width="600px"
      :bodyStyle="bodyStyle"
      centered
      @ok="changeOk"
      @cancel="changeCancel"
    >
      <a-form-model ref="changeForm" :model="changeForm" :rules="forgetRules">
        <a-form-model-item prop="oldPassword">
          <a-input
            style="height: 40px;"
            v-model="changeForm.oldPassword"
            type="password"
            placeholder="原密码"
          >
            <a-icon slot="prefix" type="lock" style="color:rgba(0,0,0,.25)" />
          </a-input>
        </a-form-model-item>
        <a-form-model-item has-feedback prop="newPassword">
          <a-input
            style="height: 40px;"
            v-model="changeForm.newPassword"
            type="password"
            placeholder="新密码"
          >
            <a-icon slot="prefix" type="lock" style="color:rgba(0,0,0,.25)" />
          </a-input>
        </a-form-model-item>
        <a-form-model-item has-feedback prop="checkNewPassword" style="margin:0;">
          <a-input
            style="height: 40px;"
            v-model="changeForm.checkNewPassword"
            type="password"
            placeholder="确认新密码"
          >
            <a-icon slot="prefix" type="lock" style="color:rgba(0,0,0,.25)" />
          </a-input>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import md5 from 'md5'
import store from 'store'
import { erpLogin, sendSmsCode, updatePassword, retrievePassword } from '@/api'

export default {
  name: 'login',
  data () {
    let validatePass = (rule, value, callback) => {
      if (value.length < 6 || value.length > 16) {
        callback(new Error('请输入6~16位新密码!'))
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass')
        }
        callback()
      }
    }
    let validatePass2 = (rule, value, callback) => {
      if (value.length < 6 || value.length > 16) {
        callback(new Error('请输入6~16位新密码!'))
      } else if (value !== this.ruleForm.pass) {
        callback(new Error('两次输入的密码不一致!'))
      } else {
        callback()
      }
    }
    let validatePass3 = (rule, value, callback) => {
      if (value.length < 6 || value.length > 16) {
        callback(new Error('请输入6~16位新密码!'))
      } else {
        if (this.changeForm.newPassword !== '') {
          this.$refs.changeForm.validateField('newPassword')
        }
        callback()
      }
    }
    let validatePass4 = (rule, value, callback) => {
      if (value.length < 6 || value.length > 16) {
        callback(new Error('请输入6~16位新密码!'))
      } else if (value !== this.changeForm.newPassword) {
        callback(new Error('两次输入的密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      form: {
        name: '',
        password: ''
      },
      ruleForm: {
        phone: '',
        code: '',
        pass: '',
        checkPass: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          {
            required: true,
            max: 11,
            message: '账户限制输入11位',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码6~16位密码', trigger: 'blur' },
          {
            required: true,
            min: 6,
            max: 16,
            message: '请输入密码6~16位密码',
            trigger: 'blur'
          }
        ]
      },
      forgetRules: {
        phone: [
          {
            required: true,
            max: 11,
            message: '请输入正确的手机号（即账号）',
            trigger: 'blur'
          }
        ],
        code: [
          {
            required: true,
            max: 6,
            message: '请输入短信验证码（6位）',
            trigger: 'blur'
          }
        ],
        pass: [{ validator: validatePass, trigger: 'change' }],
        checkPass: [{ validator: validatePass2, trigger: 'change' }],
        newPassword: [{ validator: validatePass3, trigger: 'change' }],
        checkNewPassword: [{ validator: validatePass4, trigger: 'change' }],
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' }
        ]
      },
      visible: false,
      confirmLoading: false,
      bodyStyle: {
        padding: '20px 120px'
      },
      codeStatus: false,
      count: '',
      timer: null,
      changePassword: false,
      changeForm: {
        oldPassword: '',
        newPassword: '',
        checkNewPassword: ''
      },
      account: ''
    }
  },
  methods: {
    sendCodeRequest (e) {
      sendSmsCode(e)
        .then(res => { })
        .catch(rs => { })
    },
    updatePasswordRequest (e) {
      updatePassword(e)
        .then(res => {
          if (res.code === 0) {
            this.$message.success('密码修改成功，请重新登陆！')
            setTimeout(() => {
              this.changePassword = false
            }, 200)
          }
        })
        .catch(rs => { })
    },
    resetPasswordRequest (e) {
      retrievePassword(e).then(res => {
        if (res.code === 0) {
          this.confirmLoading = false
          this.$message.success('密码重置成功！')
          setTimeout(() => {
            this.visible = false
          }, 300)
        }
      })
    },
    onSubmit () {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          // // console.log(this.form)
          const phone = this.form.name
          // // console.log(phone)
          const password = md5(this.form.password)
          // // console.log(password)
          const loginData = {
            account: phone,
            password: password
          }
          // // console.log(loginData)
          this.account = phone
          erpLogin(loginData)
            .then(res => {
              if (res.code === 0) {
                // store.set('token', res.data.token)
                // store.set('userName', res.data.name)
                // this.$router.push('/')
                if (res.data.isChange === 1) {
                  store.set('token', res.data.token)
                  store.set('headPortrait', res.data.headPortrait) // 1.2
                  store.set('userId', res.data.userId) // 1.2
                  store.set('userName', res.data.name)
                  store.set('dataRole', res.data.dataRole) // 销售下单判断
                  this.$router.push('/')
                } else {
                  this.$message.warning('首次登陆需更改密码才能使用！')
                  this.changePassword = true
                }
              }
            })
            .catch(rs => { })
        }
      })
    },
    forgetPassword () {
      this.visible = true
      this.ruleForm = {
        phone: '',
        code: '',
        pass: '',
        checkPass: ''
      }
      // this.$nextTick(() => {
      //   this.$refs.ruleForm.resetFields()
      // })
    },
    handleOk (e) {
      // 表单验证
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          if (!/^1[3456789]\d{9}$/.test(this.ruleForm.phone)) {
            this.$message.error('手机号格式不正确')
            return false
          }
          // alert('submit!')
          this.confirmLoading = true
          this.resetPasswordRequest({
            phone: this.ruleForm.phone,
            type: 1,
            password: md5(this.ruleForm.pass)
          })
        }
      })
    },
    handleCancel (e) {
      // console.log('Clicked cancel button')
      this.visible = false
      // 清空表单里面的数据
      this.$refs['ruleForm'].resetFields()
    },
    getCode () {
      const TIME_COUNT = 60
      let phone = this.ruleForm.phone
      if (!phone || !/^1[3456789]\d{9}$/.test(phone)) {
        this.$message.error('手机号格式不正确')
        return false
      }
      if (!this.timer) {
        this.count = TIME_COUNT
        this.codeStatus = true
        this.timer = setInterval(() => {
          this.count--
          if (this.count <= 0) {
            clearInterval(this.timer)
            this.codeStatus = false
            this.timer = null
          }
          // // console.log(this.count)
        }, 1000)
        this.sendCodeRequest({
          phone: phone,
          type: 'platform_modify_password'
        })
      }
    },
    changeOk () {
      let _s = this
      _s.$refs.changeForm.validate(valid => {
        if (valid) {
          let oldPassword = md5(this.changeForm.oldPassword)
          let newPassword = md5(this.changeForm.newPassword)
          _s.updatePasswordRequest({
            oldPassword: oldPassword,
            newPassword: newPassword,
            account: _s.account
          })
        }
      })
    },
    changeCancel () {
      this.changePassword = false
      this.$refs.changeForm.resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
#userLayout.user-layout-wrapper {
  height: 100%;

  &.mobile {
    .container {
      .main {
        max-width: 368px;
        width: 98%;
      }
    }
  }
  .special_img {
    margin-left: 23px;
  }
  .user-layout-login {
    label {
      font-size: 14px;
    }

    .getCaptcha {
      display: block;
      width: 100%;
      height: 40px;
    }

    .forge-password {
      font-size: 14px;
    }

    button.login-button {
      padding: 0 15px;
      font-size: 16px;
      height: 40px;
      width: 100%;
    }

    .user-login-other {
      text-align: left;
      margin-top: 24px;
      line-height: 22px;

      .item-icon {
        font-size: 24px;
        color: rgba(0, 0, 0, 0.2);
        margin-left: 16px;
        vertical-align: middle;
        cursor: pointer;
        transition: color 0.3s;

        &:hover {
          color: #1890ff;
        }
      }

      .register {
        float: right;
      }
    }
  }
  .container {
    width: 100%;
    min-height: 100%;
    background: #f0f2f5 url(../../../static/images/background.svg) no-repeat 50%;
    background-size: 100%;
    padding: 200px 0 144px;
    position: relative;

    a {
      text-decoration: none;
    }

    .top {
      text-align: center;

      .header {
        height: 33px;
        line-height: 33px;

        .badge {
          position: absolute;
          display: inline-block;
          line-height: 1;
          vertical-align: middle;
          margin-left: -12px;
          margin-top: -10px;
          opacity: 0.8;
        }

        .logo {
          width: 70px;
          height: 32px;
          vertical-align: top;
          margin-right: 12px;
          border-style: none;
        }

        .title {
          font-size: 33px;
          color: rgba(0, 0, 0, 0.85);
          font-family: Avenir, 'Helvetica Neue', Arial, Helvetica, sans-serif;
          font-weight: 600;
          position: relative;
          top: 2px;
        }

        .icon {
          width: 14px;
          height: 14px;
          vertical-align: top;
          margin-left: 7px;
        }
      }
      .desc {
        font-size: 14px;
        color: rgba(0, 0, 0, 0.45);
        margin-top: 12px;
        margin-bottom: 58px;
      }
    }

    .main {
      min-width: 260px;
      width: 368px;
      margin: 0 auto;

      .login-input {
        height: 46px;
      }

      .ant-btn {
        height: 46px;
        margin-top: 20px;
      }

      .forget-password {
        float: right;
        cursor: pointer;
        font-size: 14px;
        color: #1890ff;
      }
    }

    .footer {
      position: absolute;
      width: 100%;
      bottom: 0;
      padding: 0 16px;
      margin: 48px 0 24px;
      text-align: center;

      .links {
        margin-bottom: 8px;
        font-size: 14px;
        a {
          color: rgba(0, 0, 0, 0.45);
          transition: all 0.3s;
          &:not(:last-child) {
            margin-right: 40px;
          }
        }
      }
      .copyright {
        color: rgba(0, 0, 0, 0.45);
        font-size: 14px;
      }
    }
  }
}
</style>
